<?php


class Tag extends Model
{
	var $id = null;
	var $name;
	var $created_at;
	var $updated_at;

	function Tag()
	{
		parent::Model();
		$this->created_at = date_db_format();
	}

	function get_by_id($id)
	{
		$this->db->select('id, name, created_at, updated_at')
		         ->from('tag')
		         ->where('id', $id);
		$query = $this->db->get();
		return $query->row();
	}

	function get_by_name($name)
	{
		$this->db->select('id')
		         ->from('tag')
		         ->where('name', $name);
		$query = $this->db->get();
		return $query->row();
	}

	function update(&$object, &$data)
	{
		if (isset($data['name'])) $object->name = clean_str($data['name']);

		$errors = array();
		if (!$object->name) {
			$errors[] = 'Le nom ne peut pas être vide';
		}
		$t = $this->get_by_name($object->name);
		if ($t && $t->id != $object->id) {
			$errors[] = 'Le nom <strong>'.$object->name.'</strong> est déjà pris';
		}
		return $errors;
	}

	function save(&$object)
	{
		$object->updated_at = date_db_format();
		if ($object->id == null) {
			$res = $this->db->insert('tag', $object);
			$object->id = $this->db->insert_id();
			return $res;
		}
		else {
			$this->db->where('id', $object->id);
			return $this->db->update('tag', $object);
		}
	}

	function delete($id)
	{
		$sql = 'delete from tag
		        where id = '.intval($id).';';
		return $this->db->query($sql);
	}

	static function friendly_url($tag)
	{
		return $tag->id.'-'.url_title($tag->name);
	}
}
